<?php

namespace App\Http\Controllers\Api;

use App\Http\Services\LoginService;
use App\Repositories\Api\MemberRepository;
use Darabonba\GatewaySpi\Models\InterceptorContext\request;
use Exception;

use App\Models\Member;

// ToDo  待校验
class AuthController extends MiniAppController
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 检验会员是否存在  Todo优化
     * return token
     */
    public function get_member()
    {
        $unionid = request()->get("unionid");
        if (empty($unionid))
            return $this->apiResponse->error("参数错误");

        $member = (new MemberRepository())->getByUnionid($unionid);
        if (empty($member))
            return $this->apiResponse->error("数据异常");

        return $this->apiResponse->success($member);
    }

    /**
     * 获取会员信息
     */
    public function member()
    {

    }

    public function check_token(){
        $token = request()->get("access_token");
        if(empty($token)){
            return $this->apiResponse->error("权限不足", 410);
        }

        $loginService = new LoginService();
        $unionid = $loginService->authcode($token, "DECODE");
        if(empty($unionid)){
//            return $this->apiResponse->error("权限不足", 410);
            throw  new Exception("权限不足",410);
        }
        return true;
    }

    /**
     * 通过unionid
     * 生成access_token
     */
    public function access_token()
    {
        $unionid = request()->get("unionid", "");
        $appid = request()->get("appid", "");

        if (empty($unionid))
            return $this->apiResponse->error("unionid错误");

        if (empty($appid))
            return $this->apiResponse->error("APPID必填");

        if (!in_array($appid, ['wx307c15fc01df023c']))
            return $this->apiResponse->error("APPID不存在");

        $loginService = new LoginService();
        $token = $loginService->authcode($unionid, "ENCODE");

        return $this->apiResponse->success(['token' => $token]);
    }

}